<?php

namespace App\Services;

use App\Helpers\Redis\RedisHelper;
use App\Traits\GetLibrary\GetApiLibrary;
use App\Traits\GetModel\GetModelTrait;

class BaseService
{
    use GetModelTrait, GetApiLibrary;

    const USER_TYPE_APPLET = 10; // 小程序用户
    const USER_TYPE_STORE  = 20; // 商户用户
    const USER_TYPE_ADMIN  = 30; // 后台用户

    protected function getAreaName(...$areaList): string
    {
        $areaName = '';
        foreach ($areaList as $item) {
            if (!empty($item)) {
                if (empty($areaName)) {
                    $areaName .= $item;
                } else {
                    $areaName .= '-' . $item;
                }
            }
        }

        return $areaName;
    }

    /**
     * 添加操作锁
     *
     * @param string $sourceKey
     * @param int    $sourceId
     * @return mixed
     */
    protected function lockOperate(string $sourceKey, int $sourceId)
    {
        $redisKey = RedisHelper::makeKey(RedisHelper::STRING_LOCK_OPERATE, $sourceKey, $sourceId);
        return RedisHelper::set($redisKey , 1, ['nx', 'ex' => ONE_MINUTE * 10]);
    }

    /**
     * 删除操作锁
     *
     * @param string $sourceKey
     * @param int    $sourceId
     * @return mixed
     */
    protected function unlockOperate(string $sourceKey, int $sourceId)
    {
        $redisKey = RedisHelper::makeKey(RedisHelper::STRING_LOCK_OPERATE, $sourceKey, $sourceId);
        return RedisHelper::del($redisKey);
    }
}
